<style scoped>
.formButton {
  text-align: right;
  width: 100%;
  border-top: 1px solid #eee;
  /*margin-top: 120px;*/
  padding-top: 16px;
}
/deep/.ivu-form-item-error .ivu-filter-input .ivu-input {
  border: 1px solid #1563C2  !important;
  box-shadow: 0px 0px 8px #1563C2  !important;
}
</style>
<style>
.ql-snow.ql-toolbar button.ql-file {
  font-size: 16px;
  display: inline-block;
  font-family: Ionicons;
  speak: none;
  font-style: normal;
  font-weight: 400;
  font-variant: normal;
  text-transform: none;
  text-rendering: optimizeLegibility;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  vertical-align: -0.125em;
  text-align: center;
}
.ql-snow.ql-toolbar button.ql-file:before {
  content: '\F255';
}
</style>
<template>
  <div class="boardcast" style="padding: 10px">
    <Form ref="formValidate" :model="formValidate" :rules="formValidateRule" :label-width="100">
      <FormItem label="用户" prop="userIds">
        <Transfer
          :data="transferCompanyUsers"
          :list-style="listStyle"
          :target-keys="formValidate.userIds"
          :render-format="render2"
          :filter-method="filterMethod"
          :operations="['移除', '选择']"
          :titles="['未选用户', '已选用户']"
          filterable
          @on-change="handleChange"
        ></Transfer>
      </FormItem>
      <FormItem label="公告类型" prop="type">
        <RadioGroup v-model="formValidate.type">
          <Radio :label="1"><span class="sw">事务公告</span></Radio>
          <!--<Radio :label=2>普通公告</Radio>-->
          <Radio :label="3"><span class="wg">违规公告</span></Radio>
          <!--<Radio :label=4>系统公告</Radio>-->
        </RadioGroup>
      </FormItem>
      <FormItem label="内容" prop="content">
        <!--<Input v-model.trim="formValidate.content" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入内容"></Input>-->
        <quill-editor
          v-model="formValidate.content"
          class="editor"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)"
        >
        </quill-editor>
        <Upload
          ref="upload"
          style="display:inline-block"
          :show-upload-list="false"
          :on-success="handleSuccess"
          :on-format-error="handleFormatErrorImg"
          :format="['jpg', 'jpeg', 'png', 'gif']"
          multiple
          :action="uploadUrl"
        >
          <Button icon="ios-cloud-upload-outline" id="imgUploadBtn" v-show="false"></Button>
        </Upload>
        <Upload
          ref="fileUpload"
          style="display:inline-block"
          :show-upload-list="false"
          :on-success="handleFileSuccess"
          :on-format-error="handleFormatErrorFile"
          :format="['pdf']"
          multiple
          :action="fileUploadUrl"
        >
          <Button icon="ios-cloud-upload-outline" id="fileUploadBtn" v-show="false"></Button>
        </Upload>
      </FormItem>
      <FormItem class="formButton">
        <Button @click="cancel('formValidate')">取消</Button>
        <Button
          type="primary"
          @click="sendToUser()"
          :loading="disabledSend"
          style="margin-left: 8px"
          >发送</Button
        >
      </FormItem>
    </Form>
  </div>
</template>
<script>
//import Cookies from 'js-cookie';
import encryption from '@/libs/encryption.js';
import { quillEditor } from 'vue-quill-editor'; // 调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
//引入Qill插件
import Quill from 'quill';
let Link = Quill.import('formats/link');
// 自定义a链接
class FileBlot extends Link {
  // 继承Link Blot
  static create(value) {
    let node = undefined;
    if (value && !value.href) {
      // 适应原本的Link Blot
      node = super.create(value);
    } else {
      // 自定义Link Blot
      node = super.create(value.href);
      node.innerText = value.innerText;
      node.href = value.href;
      node.id = value.id;
      node.setAttribute('title', '点击可下载:' + value.innerText);
      node.setAttribute('data-value', value.dataValue);
    }
    return node;
  }
}
FileBlot.blotName = 'link';
FileBlot.tagName = 'A';
//注册FileBlot
Quill.register(FileBlot);
import { queryBoardCast, delBoardCast, sendToUser, sendToUserGroup } from '@/api/boardcast_new.js';
import { queryCompanyUsers, queryExperGroups, getExperGroupsUsers } from '@/api/users.js';
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  //  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  //  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: 'sub' }, { script: 'super' }], // 上标/下标
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  // [{'direction': 'rtl'}],  // 文本方向
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  //    [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ['clean'], // 清除文本格式
  ['image'], // 链接、图片、视频
  ['file'] // 文件链接
];
export default {
  components: {
    quillEditor
  },
  props: ['userList'],
  data() {
    const validateGroupUserNum = (rule, value, callback) => {
      //验证只能填入数字
      //验证警戒值
      if (value.length > 0) {
        value.forEach((group) => {
          if (group.userIds.length == 0) {
            callback(new Error('每组请至少选择一个用户'));
          } else {
            callback();
          }
        });
      } else {
        callback();
      }
    };
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    console.log(September);
    return {
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      wgimg: '',
      swimg: '',
      isloading: true,
      accessGroupList: [],
      currentPage: 1,
      boardPZ: 10,
      titleObj: {},
      searchBoard: '',
      addBoard: false,
      boardTotal: 0,
      addObj: {
        broadid: '',
        content: '',
        drillitmeinstancetaskid: '',
        drillitmetaskname: '',
        sender: September.userId,
        sendtime: '',
        teamid: '',
        title: '',
        type: 0
      },
      showBoardModel: false,
      formValidate: {
        //					"sencensType":"",
        receiverType: 1,
        //					"sceneId":this.$route.query.id,
        accessGroups: [],
        accessGroups_copy: [],
        content: '',
        id: '',
        title: '',
        type: 1,
        userIds: []
      },
      accessGroups_copy: [],
      formValidateRule: {
        sceneId: [
          {
            required: true,
            message: '请选择场景',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            type: 'number',
            message: '请选择场景类型',
            trigger: 'change'
          }
        ],
        receiverType: [
          {
            required: true,
            type: 'number',
            message: '不能为空',
            trigger: 'change'
          }
        ],
        accessGroups: [
          {
            required: true,
            type: 'array',
            min: 1,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        accessGroups_copy: [
          {
            required: true,
            type: 'array',
            min: 1,
            message: '不能为空',
            trigger: 'change'
          },
          {
            validator: validateGroupUserNum,
            trigger: 'change'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'change'
          }
        ],
        userIds: [
          {
            required: true,
            type: 'array',
            min: 1,
            message: '不能为空',
            trigger: 'change'
          }
        ]
      },
      isDisabled: true,
      isUserDisabled: true,
      showFooter: true,
      sencesUsers: [],
      sencensDrill: [],
      sencensNames: '',
      companyUsers: [],
      transferCompanyUsers: [],
      listStyle: {
        width: '240px',
        height: '300px'
      },
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, //工具菜单栏配置
            handlers: {
              image: (value) => {
                if (value) {
                  //			                  this.insertImg()
                  document.querySelector('#ImgUploadBtn').click();
                } else {
                  this.quill.format('image', false);
                }
              },
              file: (value) => {
                if (value) {
                  document.querySelector('#fileUploadBtn').click();
                }
              }
            }
          }
        },
        placeholder: this.$t('content') //提示
      },
      uploadUrl: ``,
      fileUploadUrl: '',
      setUpLoadHead: {
        Authorization: localStorage.getItem('token')
      },
      userType: 'all',
      disabledSend: false
    };
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    }
  },
  mounted() {
    this.uploadUrl = `/api/minio/upload/permanent?visibility=company&type=images&bucket=images`;
    this.fileUploadUrl = `/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs`;
    this.transferCompanyUsers = this.userList.map((user) => {
      return {
        key: user.userId,
        label: user.userName,
        nickname: user.user.nickname
      };
    });
    //发送文件图标添加title
    let fileUplodEle = document.querySelector('.ql-formats .ql-file');
    fileUplodEle.setAttribute('title', '上传pdf文件');
  },
  methods: {
    //发送图片
    handleSuccess(res) {
      if (res.code == 1) {
        // 获取光标所在位置
        let quill = this.$refs.myQuillEditor.quill;
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        let url = `/Learn/${res.data}`;
        quill.insertEmbed(length, 'image', url);
      } else {
        this.$Message.error(data.message);
      }
    },
    //发送文件
    handleFileSuccess(res) {
      if (res.code == 1) {
        // 获取光标所在位置
        let quill = this.$refs.myQuillEditor.quill;
        let length = quill.getSelection().index || 1;
        // 插入图片，res为服务器返回的图片链接地址
        let url = `${this.baseURL}/minio/download?path=${res.data}`; //`/Learn/${res.data}`
        quill.insertEmbed(length, 'text', '[');
        quill.insertEmbed(
          length + 1,
          'link',
          {
            href: url,
            innerText: res.info.originalName,
            id: res.info.id,
            dataValue: `/Learn/${res.data}`
          },
          'api'
        );
        quill.insertEmbed(length + res.info.originalName.length + 1, 'text', ']');
      } else {
        this.$Message.error(data.message);
      }
    },
    handleFormatErrorImg() {
      this.$Message.warning('仅允许上传pdf,jpg,png,gif格式文件');
    },
    handleFormatErrorFile() {
      this.$Message.warning('仅允许上传pdf格式文件');
    },
    getGroupList() {
      //				if(!testId){
      //					return;
      //				}
      let params = {
        pageIndex: 1,
        pageSize: 10000,
        order: 'desc',
        sortBy: 'created'
      };
      queryExperGroups(params).then((data) => {
        if (data.code == 1) {
          this.accessGroupList = data.data.items;
          this.formValidate.accessGroups = [];
          this.formValidate.accessGroups_copy = [];
        } else if (data.code == -2) {
          this.accessGroupList = [];
        } else {
          this.$Message.warning(data.message);
        }
      });
    },
    getAccessGroupMember(ids) {
      this.formValidate.accessGroups_copy = [];
      ids.forEach((id) => {
        let group = this.accessGroupList.filter((group) => group.id == id)[0];
        if (!group.userList) {
          getExperGroupsUsers(id).then((data) => {
            if (data.code == 1) {
              group.checkAll = false;
              this.$set(group, 'checkAll', false);
              this.$set(group, 'disabled', false);
              this.$set(group, 'groupId', group.id);
              this.$set(group, 'userList', data.data);
              this.$set(group, 'userIds', []);
            } else {
            }
          });
          this.formValidate.accessGroups_copy.push(group);
        } else {
          this.formValidate.accessGroups_copy.push(group);
        }
      });
    },
    handleCheckAll(status, group) {
      group.checkAll = !group.checkAll;
      //group.checkAll = true;
      //this.$set(group,'checkAll',!group.checkAll);
      if (group.checkAll) {
        //curGroup.userIds = group.userList.map(user => user.userId);
        group.userIds = group.userList.map((user) => user.userId);
      } else {
        group.userIds = [];
      }
    },
    checkAllGroupChange(data, group) {
      if (data.length === group.userList.length) {
        //                  this.formValidate.indeterminate = false;
        group.checkAll = true;
      } else if (data.length > 0) {
        //this.formValidate.indeterminate = true;
        group.checkAll = false;
      } else {
        //this.formValidate.indeterminate = false;
        group.checkAll = false;
      }
    },
    getBoardCastList() {
      let _this = this;
      let params = {};
      params.pageIndex = _this.currentPage || 1;
      params.pageSize = _this.boardPZ || 10;
      if (_this.searchBoard) {
        params.title = _this.searchBoard;
      }
      queryBoardCast(params).then((data) => {
        if (data.code == 1) {
          console.log(data);
          _this.boardData = data.data.items;
          _this.boardTotal = data.data.total;
        }
      });
    },
    typeFilter(type) {
      let types = '';
      if (type == 1) {
        types = '事务公告';
      }
      // else if (type == 2) {
      // 	types = '普通公告'
      // }
      else if (type == 3) {
        types = '违规公告';
      }
      // else if (type == 4) {
      // 	types = '系统公告'
      // }
      return types;
    },
    boardChangeSize(val) {
      this.boardPZ = val;
      this.getBoardCastList();
    },
    boardOnChange(val) {
      this.currentPage = val;
      this.getBoardCastList();
    },
    showAddAndUpdate(obj, type) {
      this.isloading = true;
      this.$refs.formValidate.resetFields();
      this.addBoard = true;
      if (type == 'add') {
        this.titleObj.string = '添加公告';
        this.titleObj.type = 1;
      } else {
        this.titleObj.string = '修改公告';
        this.titleObj.type = 2;
        this.titleObj.id = obj.row.id;
        let { title, content, type } = obj.row;
        this.formValidate = {
          title,
          content,
          type
        };
      }
    },
    showDel(params) {
      let _this = this;
      delBoardCast(params.row.id).then((data) => {
        if (data.code == 1) {
          _this.$Message.info('删除公告成功');
          _this.getBoardCastList();
        }
      });
    },
    sendToUser() {
      this.disabledSend = true;
      let userType = 'experimenter';
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          let params = {
            content: this.formValidate.content,
            id: '',
            status: 0,
            title: '',
            type: this.formValidate.type,
            users: [
              {
                userIds: this.formValidate.userIds
                //							      "userType": userType
              }
            ]
          };
          sendToUser(params)
            .then((data) => {
              if (data.code == 1) {
                this.$Message.info('发送成功');
                this.getBoardCastList();
                this.$emit('hideModal');
              } else {
                this.$Message.error(data.message);
              }
              this.disabledSend = false;
            })
            .catch((error) => {
              this.$Message.error('公告发送失败');
              this.disabledSend = false;
            });
        } else {
          this.disabledSend = false;
        }
      });
    },
    sendToUserGroup() {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          let params = {
            //							sceneId:this.formValidate.sceneId,
            users: this.formValidate.accessGroups_copy.map((group) => {
              return {
                userGroupType: 0,
                groupId: group.groupId,
                userIds: group.userIds,
                userType: 'designer'
              };
            }),
            content: this.formValidate.content,
            id: this.formValidate.id,
            title: this.formValidate.title,
            type: this.formValidate.type
          };
          sendToUserGroup(params).then((data) => {
            if (data.code == 1) {
              this.$Message.info('发送成功');
              this.getBoardCastList();
              this.$emit('hideModal');
            } else {
              this.$Message.error(data.message);
            }
          });
        }
      });
    },
    cancel(name) {
      this.$refs[name].resetFields();
      if (name == 'formValidate' || name == 'formValidateUser') {
        this.showBoardModel = false;
      }
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {}, // 内容改变事件
    getCompanyUsers(type) {
      let params = {
        pageIndex: 1,
        pageSize: 2147483646,
        type: type,
        order: 'desc',
        sortBy: 'created',
        type: type
      };
      if (type == 'leader' || type == 'member' || type == 'evaluator' || type == 'referee') {
        params.type = 'designer';
        params.role = type;
      } else if (type == 'all') {
        delete params.type;
      }
      //		     	this.formValidateUser.receiverType =  type;
      queryCompanyUsers(params).then((data) => {
        if (data.code == 1) {
          this.companyUsers = data.data.items;
          this.transferCompanyUsers = data.data.items.map((user) => {
            return {
              key: user.id,
              label: user.username,
              nickname: user.nickname
            };
          });
        } else {
        }
      });
    },
    filterMethod(data, query) {
      //return data.label.indexOf(query) > -1 || data.des.indexOf(query) > -1;
      return data.label.indexOf(query.trim()) > -1;
    },
    handleChange(targetKeys, direction, moveKeys) {
      this.formValidate.userIds = targetKeys;
    },
    render2(user) {
      return user.label + '<span style="float:right">' + user.nickname + '</span>';
    },
    changeReceiverType(type) {
      if (type == 2) {
        this.formValidate.accessGroups = [];
        this.formValidate.accessGroups_copy = [];
        this.formValidate.content = '';
      } else {
        this.formValidate.userIds = [];
        this.formValidate.content = '';
        //		    		this.formValidate.accessGroups_copy.forEach(group => {
        //		    			group.disabled = true;
        //		    			group.checkAll = true;
        //		    			group.userIds = group.userList.map(user => user.userId);
        //		    		})
      }
    }
  }
};
</script>
